package com.kmxy.kmxy_base;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;

import androidx.core.app.ActivityCompat;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class LocationUtil {

    private Timer timer;
    private TimerTask timerTask;

    public LocationData gpsLocationData;
    public LocationData networkLocationData;

    private Context context;
    private Handler uiHandler;


    private LocationListenerCall locationListenerCall;

    private void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (gpsLocationData == null || networkLocationData == null) {
                    return;
                }
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                // GPS15秒未获取到定位，定位异常，重启定位
                if (gpsLocationData.getTimeoutCount() >= 15) {
                    gpsLocationData.clean();
                    locationManager.removeUpdates(gpsLocationListener);
                    uiHandler.post(() -> {
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
                    });
                }
                // NET15秒未获取到定位，定位异常，重启定位
                if (networkLocationData.getTimeoutCount() >= 15) {
                    networkLocationData.clean();
                    locationManager.removeUpdates(networkLocationListener);
                    uiHandler.post(() -> {
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
                    });
                }
                if (locationListenerCall != null) {
                    if (gpsLocationData.getLatitude() != 0 && gpsLocationData.getLongitude() != 0) {
                        // GPS回调数据
                        locationListenerCall.success(gpsLocationData);
                    } else {
                        if (networkLocationData.getLatitude() != 0 && networkLocationData.getLongitude() != 0) {
                            // NET回调数据
                            locationListenerCall.success(networkLocationData);
                        } else {
                            // 定位获取失败回调
                            locationListenerCall.fail();
                        }
                    }
                }

                gpsLocationData.setTimeoutCount(gpsLocationData.getTimeoutCount() + 1);
                networkLocationData.setTimeoutCount(networkLocationData.getTimeoutCount() + 1);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    LocationManager locationManager;

    public void start(Context context, Handler uiHandler) {
        this.context = context;
        this.uiHandler = uiHandler;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
        gpsLocationData = new LocationData();
        gpsLocationData.setType(LocationManager.GPS_PROVIDER);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
        networkLocationData = new LocationData();
        networkLocationData.setType(LocationManager.NETWORK_PROVIDER);
        startTimer();
    }

    public void stop() {
        stopTimer();
        if (locationManager != null) {
            locationManager.removeUpdates(gpsLocationListener);
            locationManager.removeUpdates(networkLocationListener);
        }
        locationManager = null;
        gpsLocationData = null;
        networkLocationData = null;
    }

    public void setLocationListenerCall(LocationListenerCall locationListenerCall) {
        this.locationListenerCall = locationListenerCall;
    }


    private final LocationListener gpsLocationListener = location -> {
        makeLocation(gpsLocationData, location);
    };

    private final LocationListener networkLocationListener = location -> {
        makeLocation(networkLocationData, location);
    };

    private void makeLocation(LocationData locationData, Location location) {
        if (locationData == null) return;
        locationData.setTimeoutCount(0);
        locationData.setLatitude(location.getLatitude());
        locationData.setLongitude(location.getLongitude());
        locationData.setAltitude(location.getAltitude());
        locationData.setAddress("");
        // 使用Geocoder获取详细地址
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> addresses;
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                String addressDetails = address.getAddressLine(0);
                locationData.setAddress(addressDetails);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
